package org.chnxi.study.nio.netty.simple;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyServer {

    public static void main(String[] args) throws Exception {

        /**
         * 创建BossGroup和WorkerGroup
         * 说明：
         *  1. 创建两个线程组bossGroup和workerGroup
         *  2. bossGroup只是处理连接请求，真正和客户端业务处理，会交给workerGroup完成
         *  3. 两个都是无限循环
         *  4. bossGroup和workerGroup含有的子线程（NioEventLoop）的个数，默认是CPU核数 * 2
         */
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try{
            //创建服务器端的启动对象，配置参数
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(bossGroup , workerGroup) //设置两个线程组
                            .channel(NioServerSocketChannel.class) //使用NioSockerChannel作为服务器的通道实现
                            .option(ChannelOption.SO_BACKLOG , 128) //设置线程队列的连接个数
                            .childOption(ChannelOption.SO_KEEPALIVE , true) //设置保持活动连接状态
                            .childHandler(new ChannelInitializer<SocketChannel>() { //创建一个通道测试对象

                                //设置处理器
                                @Override
                                protected void initChannel(SocketChannel sc) throws Exception {
                                   sc.pipeline().addLast(new NettyServerHandler());
                                }
                            });
            //绑定一个端口并且同步，生成一个ChannelFuture对象
            //启动服务并绑定端口
            ChannelFuture channelFuture = serverBootstrap.bind(6666).sync();

            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if(channelFuture.isSuccess()){
                        System.out.println("监听端口6666成功");
                    }else{
                        System.out.println("监听端口6666失败");
                    }
                }
            });

            //对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }

}
